package cn.com.bob.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class TokenFilter extends ZuulFilter {

    //过滤器类型，pre代表在请求之前执行
    @Override
    public String filterType() {
        return "pre";
    }

    //过滤器执行顺序
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    //编写过滤器拦截业务逻辑代码
    @Override
    public Object run() throws ZuulException {
        //1.获取上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2.获取request
        HttpServletRequest request = currentContext.getRequest();
        //3.获取token的时候 从请求头获取
        String uerToken = request.getParameter("userToken");
        if(StringUtils.isEmpty(uerToken)){
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseBody("userToken is null");
            currentContext.setResponseStatusCode(401);
            return null;
        }
        return null;
    }
}
